/**
 * useage
 * 
 * this.use("dai","demo");
 * 
 * this.demodai = this.dai.create("demo");
 * 
 * this.demodai.add({...});
 * this.demodai.remove({...});
 * 
 */

;(function(){
	var $ = window.jQuery || window.Zepto || window;
	function Dai(model_name){
		this.model_name = model_name;
	}

	Dai.prototype = {
		add : function(data,callback){
			$.ajax({
				url : "/dai/add/"+ this.model_name,
				data : data,
				type : "post",
				success : callback
			});
		},
		addbatch : function(list,callback){
			$.ajax({
				url : "/dai/addbatch/"+ this.model_name,
				data : {datas:JSON.stringify(list)},
				type : "post",
				success : callback
			});
		},
		query : function(data,callback){
			$.ajax({
				url : "/dai/query/"+ this.model_name,
				data : data,
				type : "get",
				success : callback
			});
		},
		get : function(id,callback){
			$.ajax({
				url : "/dai/get/"+this.model_name+"/"+id,
				type : "get",
				success : callback
			});
		},
		update : function(query,data,callback){
			$.ajax({
				url : "/dai/update/"+this.model_name+"?"+$.param(query),
				type : "post",
				data : data,
				success : callback
			});
		},
		remove : function(data,callback){
			$.ajax({
				url : "/dai/remove/"+ this.model_name,
				type : "get",
				data : data,
				success : callback
			});
		},
		action : function(action,data,callback){
			$.ajax({
				url : "/dai/action/"+ action +"/"+this.model_name,
				type : "post",
				data : data,
				success : callback
			});
		}
	}

	var dai_cache = {};

	H5x.plugin("dai",function(component,opts){		
		component.dai = {
			opts : opts||{},
			create : function(model_name){
				var global_app_name = $("input[name='global_app_name']").val();
				model_name = (this.opts.app_name || global_app_name) + "_"+model_name;
				//console.log(model_name);

				if(!dai_cache[model_name]){
					dai_cache[model_name] = new Dai(model_name);
				}

				return dai_cache[model_name];
			}
		};
		return component.dai;
	});
})();
